package com.alorm.sqlite;

import java.util.ArrayList;

import com.alorm.core.exceptions.AlormException;
import com.alorm.core.sqlgen.DataBaseSchemaGenerator;
import com.alorm.core.sqlgen.SqlStatementsGenerator;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDB extends SQLiteOpenHelper {

	private int baseVersion;
	private String baseNom;

	private SQLiteDatabase sqLiteDatabase;

	private SqlStatementsGenerator sqlStatementsGenerator;
	private DataBaseSchemaGenerator dBschemaGenerator;

	private static MyDB myDB ;

	private MyDB(Context context, String baseNom, CursorFactory factory,
			int baseVersion) {
		super(context, baseNom, factory, baseVersion);
		this.baseVersion = baseVersion;
		this.baseNom = baseNom;

		dBschemaGenerator = new DataBaseSchemaGenerator(context);
		sqlStatementsGenerator = new SqlStatementsGenerator(dBschemaGenerator);

	}

	public void onCreate(SQLiteDatabase arg0) {

	}

	public void crateSchema() throws AlormException {
		ArrayList<String> reqSQL = dBschemaGenerator.CreatTables();
		for (String req : reqSQL) {
			sqLiteDatabase.execSQL(req);
		}

	}

	public void save(Object object) throws AlormException {
		String reqSQL = sqlStatementsGenerator.getSaveStatement(object);
		sqLiteDatabase.execSQL(reqSQL);

	}

	public void update(Object object) throws AlormException {
		String reqSQL = sqlStatementsGenerator.getUpdateStatement(object);
		sqLiteDatabase.execSQL(reqSQL);

	}

	public void delete(Object object) throws AlormException {
		String reqSQL = sqlStatementsGenerator.getDeleteStatement(object);
		sqLiteDatabase.execSQL(reqSQL);
	}

	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {

	}

	public SQLiteDatabase open() {
		sqLiteDatabase = this.getWritableDatabase();
		return sqLiteDatabase;
	}

	public void close() {
		sqLiteDatabase.close();
	}

	public int getBaseVersion() {
		return baseVersion;
	}

	public void setBaseVersion(int baseVersion) {
		this.baseVersion = baseVersion;
	}

	public String getBaseNom() {
		return baseNom;
	}

	public void setBaseNom(String baseNom) {
		this.baseNom = baseNom;
	}

	public static MyDB getMyDB(Context context, String baseNom,
			CursorFactory factory, int baseVersion) {
		return new MyDB(context, baseNom, factory, baseVersion);

	}

	public static void setMyDB(MyDB myDB) {
		MyDB.myDB = myDB;
	}
	

}
